//
//  KLocateCommand.m
//  Keping
//
//  Created by 柯平 on 2017/6/18.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KLocateCommand.h"
#import "SystemInfo.h"

@implementation KLocateCommand

-(void)cancel
{
    [self stopUpdatingLocation];
    [geocoder cancelGeocode];
    [super cancel];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)execute
{
    [[KAppConfig sharedConfig] setLocationStatus:[CLLocationManager authorizationStatus]];
    if (![CLLocationManager locationServicesEnabled]) {
        self.responseStatus = KLocateStatusServiceUnable;
        KLog(@"定位服务不可用");
    }else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied){
        self.responseStatus = KLocateStatusUserDenied;
        KLog(@"用户不允许定位");
    }else{
        [[KAppConfig sharedConfig] setLocationAuthorized:YES];
        [self startUpdatingLocation];
    }
}

-(void)startUpdatingLocation
{
    if (!manager) {
        manager = [[CLLocationManager alloc] init];
        manager.delegate = self;
    }
    if (IOS8_OR_LATER) {
        [manager requestWhenInUseAuthorization];
    }
    
    [manager startUpdatingLocation];
    
    //time out
    [self performSelector:@selector(stopUpdatingLocation) withObject:nil afterDelay:self.timeOutDefault > 0 ? self.timeOutDefault : 60];
}

-(void)stopUpdatingLocation
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(stopUpdatingLocation) object:nil];
    
    [manager stopUpdatingLocation];
}

#pragma mark - CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation* location = [locations lastObject];
    self.coordinate = location.coordinate;
    [[KAppConfig sharedConfig] setLongitude:location.coordinate.longitude];
    [[KAppConfig sharedConfig] setLatitude:location.coordinate.latitude];
    if (!geocoder) {
        geocoder = [[CLGeocoder alloc] init];
    }
    
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error && [placemarks count]) {
            self.responseStatus = KLocateStatusAddressFail;
        }else{
            for (CLPlacemark* placeMark in placemarks) {
                self.addressInfoDic = placeMark.addressDictionary;
                NSString* locatedCity = [placeMark.addressDictionary objectForKey:@"City"];
                if (![locatedCity isNotBlank]) {
                    locatedCity = [placeMark.addressDictionary objectForKey:@"State"];
                }
                self.cityName = locatedCity;
#warning 定位成功
                [[NSNotificationCenter defaultCenter] postNotificationName:@"KLocatedSuccessNotificationKey" object:nil];
                break;
            }
        }
        [self done];
    }];
    [self stopUpdatingLocation];
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    KLog(@"Locate Error:%@",error);
    [self stopUpdatingLocation];
    self.responseStatus = KLocateStatusFail;
    [self done];
}

+(void)saveLocatedCity:(NSString *)cityName
{
    KLog(@"保存定位城市：%@",cityName);
}

@end
